import { _decorator, instantiate, Prefab, Vec3 } from 'cc';
import PlantBase from './PlantBase';
import { EventBus,TYPE } from './Utils/EventBus'
const { ccclass, property } = _decorator;

@ccclass('ShoterBase')
export default class ShoterBase extends PlantBase {
  // 子弹预制体
  @property(Prefab)
  bulletPrefab: Prefab = null!;

  // 每次发射几发子弹
  @property
  bulletCount: number = 1;

  // 设计间隔(秒)
  @property
  shooterInterval: number = 2;

  // 多发子弹的水平偏移量
  @property
  bulletSpacing: number = 10;

  private shooterTimer: number = 0;


  public isShoot:boolean = false


  protected start(): void {
      EventBus.once(TYPE.PLANTING_SUCCESS,()=>{
        console.log("监听到种植成功消息")
        this.playAction('attack')
        this.isShoot = true
      })
  }


  update(dt: number) {
    this.updateAnimation(dt);
    this.shooterTimer += dt;
    if (this.shooterTimer >= this.shooterInterval && this.isShoot) {
      this.shoot();
      this.shooterTimer = 0;
    }
  }

  shoot() {
    if (!this.bulletPrefab) return;
    for (let i = 0; i < this.bulletCount; i++) {
        this.scheduleOnce(() =>{
            this.spawnBullet()
        },i * 0.3)
    }
  }


  private spawnBullet() {
    const bullet = instantiate(this.bulletPrefab)
    // 挂载到场景中
    bullet.setParent(this.node.parent)
    // 获取植物的世界坐标
    const worldPos = this.node.worldPosition.clone()
    bullet.setWorldPosition(worldPos.x + 30, worldPos.y + 20, worldPos.z);
  }
}
